package qs.openxt.libs.record;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import qs.openxt.libs.R;
import qs.openxt.libs.fragment.BaseActivity;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/3/23.
 */
public class QTRecordActivity extends BaseActivity {
    private Button record;
    private Dialog dialog;
    private QTAudioRecorder mr;
    private Thread recordThread;

    private static int MAX_TIME = -1;    //最长录制时间，单位秒，-1为无时间限制
    private static int MIX_TIME = 1;     //最短录制时间，单位秒，0为无时间限制，建议设为1

    private static int RECORD_NO = 0;  //不在录音
    private static int RECORD_ING = 1;   //正在录音
    private static int RECODE_ED = 2;   //完成录音

    private static int RECODE_STATE = 0;      //录音的状态

    private static float recodeTime = 0.0f;    //录音的时间
    private static double voiceValue = 0.0;    //麦克风获取的音量值

    public static final String AUDIO_TIME = "AUDIO_TIME";

    private ImageView dialog_img;

    private String mFlie = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        customStyle(R.layout.record_audio, "录音", true);

        Intent intent = getIntent();
        String time = intent.getStringExtra(AUDIO_TIME);
        if(StringUtil.isNull(time))
            time = "-1";
        MAX_TIME = Integer.valueOf(time);

        record = (Button) this.findViewById(R.id.record);

        //录音
        record.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (RECODE_STATE != RECORD_ING) {
                            mFlie = Utils.getFile("raw").getAbsolutePath();
                            mr = new QTAudioRecorder(mFlie);
                            RECODE_STATE = RECORD_ING;
                            showVoiceDialog();
                            try {
                                mr.start();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            startRecordThread();
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        if (RECODE_STATE == RECORD_ING) {
                            RECODE_STATE = RECODE_ED;
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            try {
                                mr.stop();
                                voiceValue = 0.0;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (recodeTime < MIX_TIME) {
                                showWarnToast();
                                record.setText("按住开始录音");
                                RECODE_STATE = RECORD_NO;
                                recodeTime = 0.0f;
                            } else {
                                record.setText("录音完成!");
                                recodeTime = 0.0f;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent();
                                        intent.putExtra("path", mFlie);
                                        setResult(RESULT_OK, intent);

                                        finish();
                                    }
                                });
                            }
                        }

                        break;
                    case MotionEvent.ACTION_CANCEL: {
                        if (RECODE_STATE == RECORD_ING) {
                            RECODE_STATE = RECODE_ED;
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            try {
                                mr.stop();
                                voiceValue = 0.0;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            showWarnToast();
                            record.setText("按住开始录音");
                            RECODE_STATE = RECORD_NO;
                            recodeTime = 0.0f;
                        }
                        break;
                    }
                }
                return false;
            }
        });
    }

    protected void onDestroy(){
        try {
            mr.stop();
        }catch (Exception e){

        }
        super.onDestroy();
    }


    //录音时显示Dialog
    void showVoiceDialog() {
        dialog = new Dialog(this, R.style.DialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        dialog.setContentView(R.layout.my_dialog);
        dialog_img = (ImageView) dialog.findViewById(R.id.dialog_img);
        dialog.show();
    }

    //录音时间太短时Toast显示
    void showWarnToast() {
        new File(mFlie).delete();

        Toast toast = new Toast(this);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setPadding(20, 20, 20, 20);

        // 定义一个ImageView
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.voice_to_short); // 图标

        TextView mTv = new TextView(this);
        mTv.setText("时间太短   录音失败");
        mTv.setTextSize(14);
        mTv.setTextColor(Color.WHITE);//字体颜色
        //mTv.setPadding(0, 10, 0, 0);

        // 将ImageView和ToastView合并到Layout中
        linearLayout.addView(imageView);
        linearLayout.addView(mTv);
        linearLayout.setGravity(Gravity.CENTER);//内容居中
        linearLayout.setBackgroundResource(R.mipmap.record_bg);//设置自定义toast的背景

        toast.setView(linearLayout);
        toast.setGravity(Gravity.CENTER, 0, 0);//起点位置为中间     100为向下移100dp
        toast.show();
    }

    //录音计时线程
    void startRecordThread() {
        recordThread = new Thread(ImgThread);
        recordThread.start();
    }

    //录音Dialog图片随声音大小切换
    void setDialogImage() {
        long v = Math.round(voiceValue * 1.7);
        if(v == 1){
            dialog_img.setImageResource(R.mipmap.record_animate_01);
        }else if(v == 2){
            dialog_img.setImageResource(R.mipmap.record_animate_02);
        }else if(v == 3){
            dialog_img.setImageResource(R.mipmap.record_animate_03);
        }else if(v == 4){
            dialog_img.setImageResource(R.mipmap.record_animate_04);
        }else if(v == 5){
            dialog_img.setImageResource(R.mipmap.record_animate_05);
        }else if(v == 6){
            dialog_img.setImageResource(R.mipmap.record_animate_06);
        }else if(v == 7){
            dialog_img.setImageResource(R.mipmap.record_animate_07);
        }else if(v == 8){
            dialog_img.setImageResource(R.mipmap.record_animate_08);
        }else if(v == 9){
            dialog_img.setImageResource(R.mipmap.record_animate_09);
        }else if(v == 10){
            dialog_img.setImageResource(R.mipmap.record_animate_10);
        }else if(v == 11){
            dialog_img.setImageResource(R.mipmap.record_animate_11);
        }else if(v == 12){
            dialog_img.setImageResource(R.mipmap.record_animate_12);
        }else if(v == 13){
            dialog_img.setImageResource(R.mipmap.record_animate_13);
        }else if(v == 14){
            dialog_img.setImageResource(R.mipmap.record_animate_14);
        }

    }

    //录音线程
    private Runnable ImgThread = new Runnable() {
        @Override
        public void run() {
            recodeTime = 0.0f;
            while (RECODE_STATE == RECORD_ING) {
                if (recodeTime >= MAX_TIME && MAX_TIME != -1) {
                    imgHandle.sendEmptyMessage(0);
                } else {
                    try {
                        Thread.sleep(100);
                        recodeTime += 0.1;
                        if (RECODE_STATE == RECORD_ING) {
                            voiceValue = mr.getAmplitude();
                            imgHandle.sendEmptyMessage(1);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        Handler imgHandle = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        //录音超过15秒自动停止
                        if (RECODE_STATE == RECORD_ING) {
                            RECODE_STATE = RECODE_ED;
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            try {
                                mr.stop();
                                voiceValue = 0.0;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (recodeTime < MIX_TIME) {
                                showWarnToast();
                                record.setText("按住开始录音");
                                RECODE_STATE = RECORD_NO;
                            } else {
                                record.setText("录音完成!");
                                recodeTime = 0.0f;
                                showMsg("录音超过最大" + MAX_TIME + "秒，自动停止录音");
                                imgHandle.sendEmptyMessageDelayed(9, 1500);
                            }
                        }
                        break;
                    case 1:
                        setDialogImage();
                        break;
                    case 9:{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent();
                                intent.putExtra("path", mFlie);
                                setResult(RESULT_OK, intent);

                                finish();
                            }
                        });
                        break;
                    }
                    default:
                        break;
                }
            }
        };
    };
}
